<template>
  <el-card class="good-container">
    <template #header>
      <div class="header">
        <div class="search-container">
          <el-input
              v-model="state.searchValue"
              placeholder="资讯标题关键字"
              clearable
              style="width: 180px; margin-left: 30px;margin-right: 10px"
          />
          <el-select
              v-model="state.categoryId"
              placeholder="请选择分类"
              @click="handleOption"
              style="width: 170px"
              class="category-selector">
            <el-option
                v-for="category in state.categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id"/>
          </el-select>
          <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
          <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>


        </div>
        <div class="action-buttons">
          <el-button type="primary" color="red" @click="handleAdd">增加</el-button>
          <el-popconfirm
              title="确定要批量删除吗？"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="AllDetele"
          >
            <template #reference>
              <el-button type="primary" color="#FF3D3D" size="size" style="margin-left: 6px">
                批量删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </template>

    <el-table
        :loading="state.loading"
        :data="state.tableData"
        :key="tableKey"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="序号"
          align="center"
          width="60"
      >
        <template #default="scope">
          {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
          prop="title"
          align="center"
          label="标题"
      >
      </el-table-column>
      <el-table-column
          prop="summary"
          align="center"
          label="简介"
      >
      </el-table-column>

      <el-table-column
          label="封面"
          align="center"
          width="140"
      >
        <template #default="scope">
          <img style="width: 80px; height: 80px;border-radius: 12px" :key="scope.row.id"
               :src="$filters.prefix(scope.row.cover)" alt="图">
        </template>
      </el-table-column>


      <el-table-column label="内容" align="center" width="150" prop="content">
        <template #default="scope">
          <el-button type="warning" size="small" @click="ShowContent(scope.row.content)">
            查看内容
          </el-button>
        </template>

      </el-table-column>

      <el-table-column
          prop="publishTime"
          align="center"
          label="发布时间"
      >
      </el-table-column>
      <el-table-column
          prop="viewCount"
          align="center"
          label="浏览次数"
          width="100"
      >
      </el-table-column>
      <el-table-column
          prop="categoryName"
          label="分类"
          width="200"
          align="center"
      >
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <!-- 编辑按钮 -->
            <el-button
                type="warning"
                size="small"
                :icon="Edit"
                :disabled="scope.row.id === '1'"
                @click="handleEdit(scope.row.id)">
              编辑
            </el-button>

            <!-- 删除按钮（带确认） -->
            <el-popconfirm
                title="确定要删除此项吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDeleteOne(scope.row.id)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    :disabled="scope.row.id === '1'"
                    style="margin-left: 8px">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>

    </el-table>
    <!--总数超过一页，再展示分页器-->
    <el-pagination
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
    />
  </el-card>
  <!--  编辑弹窗控件-->
  <InformationInfoDialog ref='informationInfoDialog' :reload="getGoodList" :type="state.type"
                         :configType="state.configType"/>

  <el-dialog title="内容" v-model="fromVisible" width="50%">
    <div>
      <div v-html="state.content"></div>
    </div>
    <div slot="footer" class="dialog-footer">
      <span>
        <el-button style="float: right" type="primary" @click="fromVisible =false">确 定</el-button>
      </span>
    </div>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref, getCurrentInstance} from 'vue'
import {ElMessage} from 'element-plus'
import {Plus, Delete, Edit} from '@element-plus/icons-vue'
import {useRouter} from 'vue-router'
import dayjs from 'dayjs';
import {
  listInfoNews, addInfoNews,
  deleteInfoNewsById, getInfoNewsById, batchDeleteInfoNews
} from '../../service/infoNewsApi';
import {pageInfoCategory} from '../../service/infoCategoryApi.js'
import InformationInfoDialog from "../../components/InformationInfoDialog.vue";
// 在 setup 中定义 tableKey
const tableKey = ref(0);
const fromVisible = ref(false)
const app = getCurrentInstance()
const {goTop} = app.appContext.config.globalProperties
const informationInfoDialog = ref(null)
const router = useRouter()
const state = reactive({
  searchValue: '', // 新增搜索值
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 5, // 分页大小
  categoryList: [], // 分类列表
  content: ''//内容存储
})
// 打开新增表单
const handleAdd = () => {
  state.type = 'add'
  informationInfoDialog.value.open();
};
// 获取分类列表数据
const handleOption = async () => {
  const params = {
    pageNum: 1,
    pageSize: 100,
    name: '',
  };

  const response = await pageInfoCategory(params);
  state.categoryList = response.data.records || []
};

// 打开编辑表单
const handleEdit = (id) => {
  console.log('handleEdit', id)
  state.type = 'edit'
  informationInfoDialog.value.open(id);
}

// 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val
}

// 删除资讯
const handleDeleteOne = async (id) => {
  try {
    await deleteInfoNewsById(id);
    ElMessage.success('删除成功');
    await getGoodList(); // 刷新数据
  } catch (error) {
    console.error('删除失败', error);
    ElMessage.error('删除失败');
  }
};
// 分页变化
const changePage = async (val) => {
  state.currentPage = val;
  await getGoodList();
};
// 获取取资讯列表
const getGoodList = async () => {
  state.loading = true;
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
    title: state.searchValue,
    categoryId: state.categoryId
  };
  try {
    // 查询资讯分类列表数据
    const response = await listInfoNews(params);
    if (response && response.data) {
      // 确保日期格式正确，如果需要可以在这里进行转换
      const formattedRecords = response.data.records.map(item => {
        return {
          ...item,
          publishTime: dayjs(item.publishTime).format('YYYY-MM-DD HH:mm:ss')
        };
      });
      state.tableData = formattedRecords;
      state.total = response.data.total || 0;
      tableKey.value++;
      state.content =state.tableData.content
    } else {
      console.error('响应数据格式错误:', response);
      state.tableData = [];
      state.total = 0;
    }
  } catch (error) {
    console.error('获取资讯列表失败:', error);
    state.tableData = [];
    state.total = 0;
  } finally {
    state.loading = false;
  }
};


onMounted(() => {
  getGoodList();
});

// 搜索处理
const handleSearch = () => {
  state.currentPage = 1
  getGoodList();
}
const handleReset = async () => {
  state.searchValue = '';
  state.categoryId = '';
  await getGoodList(); // 刷新数据
}
// 批量删除
const AllDetele = async () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择项')
    return
  }
  const response = await batchDeleteInfoNews(state.multipleSelection.map(item => item.id));
  if (response.code === 200) {
    ElMessage.success('删除成功')
    await getGoodList()
  } else {
    ElMessage.error('删除失败')
  }
}


const ShowContent = (content) => {
  fromVisible.value = true
  state.content = content

};
</script>

<style scoped>
.good-container {
  min-height: 100%;
}

.el-card.is-always-shadow {
  min-height: 100% !important;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  /* position: relative; */
  display: flex;
  align-items: center;
}

.cover {
  border: 1px solid #FFFFFF;
  border-radius: 10px;
  width: 100px;
  height: 100px;
}

.search-container .el-button {
  margin-left: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end; /* 将内容推到容器末尾 */
  align-items: center; /* 垂直居中 */
}
</style>